<template>
	<cu-custom bgColor="" :isBack="true">
		<template #title>任务日志</template>
	</cu-custom>
	
	<view class="cu-timeline">
		<!-- <view class="cu-time">昨天</view> -->
		<view v-for="(item, index) in dataList"
			:key="index"
			:class="{
				'cu-item': item.type === 'default',
				'text-white': item.type === 'default',
				'cu-time': item.type === 'date'
			}"
		>
			<view class="content shadow-blur" v-if="item.type === 'default'">
				<text>{{ item.time }}</text>&nbsp;{{ item.title }}
			</view>
			<view v-else>
				{{ item.date }} 
			</view>
			<view v-if="item.files && item.files.length > 0" class="file-box">
				<view v-for="(file, index) in item.files" @click="previewFile(file)" :key="index" class="file-icon">
					<image :src="calFileView(file)" mode="aspectFill"></image>
					<view class="file-name text-ellipsis-2">{{ file.name }}</view>
				</view>
			</view>
			<view class="voice-content" v-if="item.media_id" @click="navToVoice(item)">
				<view class="play-voice">
					<image src="/static/images/voice_white.png" mode="aspectFill" />
					{{ item.duration }}"
				</view>
			</view>
			<!-- <view v-if="item.media_id">
				<VoicePlay :voice="item" />
			</view> -->
			
			<view v-if="userInfo.role === 1 && item.userId !== userInfo.id && item.status === '0'"
				class="hint-box" @click="handleRecord(item)">
				<text>{{ item.userName }} 提交</text>
				<text>点击处理资料<text class="cuIcon-right"></text></text>
			</view>
			<view v-if="recordHintShow(item)" class="hint-box-role2 flex justify-between">
				<text>{{ item.userName }} 提交</text>
				<text v-if="item.status === '0'" style="color: #f1a56a">待确认</text>
				<text v-else class="text-white">已确认</text>
			</view>
			
			<view v-if="item.record_type === '3'" class="hint-box" @click="navToStatistics">
				<text>点击查看</text>
				<text class="cuIcon-right"></text>
			</view>
			<view v-if="item.record_type === '4'" class="hint-box" @click="navToRect(item)">
				<text>查看整改进度</text>
				<text class="cuIcon-right"></text>
			</view>
		</view>
	</view>
	
	<Dialog
		message="确认材料"
		cancelable
		v-model:show="dialogShow"
		@confirm="handleConfirm"
		@cancel="handleCancel"
	/>
	
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app"
import { getMissionRecord } from "@/api/mission.js"
import { reactive, ref, type Ref } from "vue"
import { obj2str } from "@/utils/base"
import { updateRecordStatus } from "@/api/mission.js"
import env from "@/env"
import Dialog from "@/components/Dialog.vue"
import store from "@/store/index.js"
import { router } from "@/router"
import VoicePlay from "@/components/VoicePlay.vue"
import { IFile } from "@/interface/IFile"
import { IRecord } from "@/interface/IRecord"
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

const props = defineProps({
	mission_id: {
		type: String,
		default: null
	}
})
const dialogShow:Ref<boolean> = ref(false)
const dataList:Ref<IRecord[]> = ref([] as IRecord[])
const userInfo = reactive({ ...store.getters.userInfo })

const recordingFinished:Ref<boolean> = ref(false)
let autoStopTimeout = null
let recordingDownloadFinished = false
let playingLoading = false
const voiceData:any = reactive({
	mediaId: "",
	localAudioId: null
})

let mission_id = null
let form_id = null

/**
 * 是否显示每条消息的底部提示
 */
const recordHintShow = (item: IRecord) => {
	if (item.type === "date") return false
	if (userInfo.role === 1) {
		if (item.userId && item.userId !== userInfo.id) {
			return item.status === "1"
		} else {
			return false
		}
	} else {
		return item.userId === userInfo.id
	}
}

/**
 * 加载数据
 */
const loadData = ():void => {
	getMissionRecord(mission_id)
		.then((res:any):void => {
			dialogShow.value = false
			dataList.value = []
			const data = res.records
			form_id = res.formId
			data.map((item) => {
				const date = (new Date(item.time))
				const day = date.format("MM-dd")
				if (!dataList.value.length || dataList.value[dataList.value.length - 1].date !== day) {
					dataList.value.push({
						type: "date",
						date: day,
						year: date.getFullYear()
					})
				}
				
				let files = []
				if (item.fileUrl) {
					files = JSON.parse(item.fileUrl)
					files.map((file) => {
						file.suffix = file.name.match(/\.[^.]+$/g)[0].substring(1).toLowerCase()
					})
				}
				
				
				dataList.value.push({
					id: item.id,
					type: "default",
					record_type: item.type,
					year: date.getFullYear(),
					date: date.format("MM-dd"),
					time: date.format("hh:mm"),
					title: item.title,
					files: files,
					media_id: item.mediaId,
					duration: item.duration,
					status: item.status,
					userId: item.userId,
					userName: item.userName
				})
			})
			console.log(dataList.value)
		})
		.catch((err) => {
			dialogShow.value = false
		})
}
const calFileView = (file:IFile) => {
	if (file.suffix === "jpg" || file.suffix === "png" || file.suffix === "jpeg") {
		return file.url
	} else if (file.suffix === "docx") {
		return env.H5_RELATIVE_URL + "/static/images/docx_icon.png"
	} else {
		return env.H5_RELATIVE_URL + "/static/images/otherfile_icon.png"
	}
}
const previewFile = (file:IFile) => {
	console.log(file.suffix)
	if (file.suffix === "jpg" || file.suffix === "png" || file.suffix === "jpeg") {
		uni.previewImage({
			urls: [file.url],
			current: file.url
		})
	} else if (file.suffix === "docx") {
		// #ifdef MP-ALIPAY
		const query = obj2str({
			filepath: file.url,
		})
		// console.log(env.MINI_APP_URL + "pages/index/word?" + query)
		dd.openLink({
			url: `${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/word?" + query)}`
		}).then((res:any) => {
			console.log("success")
			console.log(res)
		}).catch((err:any) => {
			console.log("error")
			console.log(err)
		})
		// #endif
		// #ifdef H5
		if (store.getters.osName === "ios") {
			router.push("/pages/index/word?title=" + file.name + "&filepath=" + file.url)
		} else {
			location.href = file.url
		}
		// #endif
	} else {
		location.href = file.url
	}
}
let currRecordId = null
const handleRecord = (item) => {
	dialogShow.value = true
	currRecordId = item.id
}
const handleConfirm = () => {
	uni.showLoading({
		title: "处理中"
	})
	updateRecordStatus(currRecordId)
		.then((res: any) => {
			uni.showToast({
				icon: "success",
				title: "操作成功"
			})
			loadData()
		})
}

const handleCancel = () => {
	console.log("暂未接入否决")
}
const navToStatistics = () => {
	router.push("/pages/mission/statistics?form_id=" + form_id)
}
const navToRect = (item: any) => {
	router.push("/pages/mission/rectification?record_id=" + item.id)
}
const navToVoice = (item: IRecord) => {
	// #ifdef MP-ALIPAY
	const query = obj2str({
		mediaId: item.media_id,
		duration: item.duration,
	})
	dd.openLink({
		url: `${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/play?" + query)}`
	}).then((res:any) => {
		console.log("success")
		console.log(res)
	}).catch((err:any) => {
		console.log("error")
		console.log(err)
	})
	// #endif
	// #ifdef H5
	voiceData.mediaId = item.media_id
	playVoice(item)
	// #endif
}

const downloadVoice = ():Promise<void> => {
	return new Promise((resolve, reject):void => {
		dd.downloadAudio({
		  mediaId: voiceData.mediaId
		}).then((res:any) => {
			voiceData.localAudioId = res.localAudioId
			recordingFinished.value = true
			recordingDownloadFinished = true
			resolve()
		}).catch((err:any) => {
			uni.showToast({
				icon: "none",
				title: "录音下载失败" + JSON.stringify(err)
			})
			reject()
		})
	})
}

const playVoice = async (item: IRecord) => {
	if (!recordingDownloadFinished) {
		await downloadVoice()
	}
	if (playingLoading) return
	if (item.playing) {
		playingLoading = true
		dd.stopAudio({
			localAudioId : voiceData.localAudioId,
		}).then(() => {
			playingLoading = false
			item.playing = false
			clearTimeout(autoStopTimeout)
		}).catch((err) => {
			playingLoading = false
			uni.showToast({
				icon: "none",
				title: "录音停止失败" + JSON.stringify(err)
			})
		})
	} else {
		playingLoading = true
		dd.playAudio({
			localAudioId : voiceData.localAudioId,
		}).then(() => {
			uni.showToast({
				icon: "none",
				title: "正在播放"
			})
			item.playing = true
			playingLoading = false
			autoStopTimeout = setTimeout(() => {
				item.playing = false
			}, voiceData.duration * 1000)
		}).catch(err => {
			playingLoading = false
			// uni.showToast({
			// 	icon: "none",
			// 	title: "录音播放失败" + JSON.stringify(err)
			// })
		})
	}
}
	
onLoad((options:any) => {
	if (options.mission_id) {
		mission_id = options.mission_id
		loadData()
	}
})
</script>

<style lang="stylus" scoped>
body
	background-color #3974df
.cu-timeline
	background-color: unset
.cu-timeline > .cu-item::before
	background-color: #3974df
.cu-timeline > .cu-item .content
	background-color: #5789e4
	color: #ffffff
.cu-time
	color: #ffffff
	font-size: 32rpx;
	font-weight: 400
	
.file-box
	margin-top: 10rpx
	border-radius: 6rpx
	background-color: #5789e4
	display: flex
	box-sizing: border-box
	padding: 20rpx 40rpx
	.file-icon
		width: 25%
		text-align: center
		image
			height 120rpx
			width 120rpx

.voice-content
	margin-top: 10rpx
	border-radius: 6rpx
	display: flex
	align-items: center
	background-color: #5789e4
	box-sizing: border-box
	padding: 10rpx 20rpx
	justify-content: space-between
	.play-voice
		height: 66rpx
		width: 430rpx
		border-radius: 12rpx
		display: flex
		align-items: center
		font-weight: bold
		color #fff
		image
			width: 44rpx
			height: 44rpx
			padding: 11rpx
			margin-right: 10rpx
.voice-content:active
	background-color: #447de4

.hint-box
	margin-top 10rpx
	background darkcyan
	border-radius: 6rpx
	box-sizing: border-box
	padding: 30rpx
	display: flex
	justify-content: space-between
	transition: background .3s
.hint-box:active
	background: #006e6e
.hint-box-role2
	margin-top 10rpx
	background darkcyan
	border-radius: 6rpx
	box-sizing: border-box
	padding: 30rpx
	display: flex
	justify-content: space-between
	transition: background .3s
</style>